package com.example.module.ai.tencent.websocket;

import com.example.module.ai.config.TencentAppProperties;
import com.tencentcloudapi.common.CommonClient;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

@Service
public class DeepSeekAppTencentTokenService {

    @Resource
    private TencentAppProperties tencentAppProperties;

    @SneakyThrows
    public String getWsToken() {
        CommonClient client = getCommonClient();
        JSONObject params = new JSONObject();
        params.put("Type", tencentAppProperties.getConnTypeApi());
        params.put("BotAppKey", tencentAppProperties.getBotAppkey());
        params.put("VisitorBizId", tencentAppProperties.getVisitorBizId());
        String respJsonStr = client.call("GetWsToken", params.toString());

        JSONObject resp = new JSONObject(respJsonStr);
        JSONObject respData = resp.getJSONObject("Response");
        return respData.getString("Token");
    }

    @NotNull
    private CommonClient getCommonClient() {
        Credential cred = new Credential(tencentAppProperties.getSecretId(), tencentAppProperties.getSecretKey());

        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setRootDomain("tencentcloudapi.com");
        httpProfile.setReqMethod(HttpProfile.REQ_POST);
        httpProfile.setProtocol(HttpProfile.REQ_HTTPS);

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        return new CommonClient("lke", "2023-11-30", cred, "ap-guangzhou", clientProfile);
    }

}
